606. 根据二叉树创建字符串

606. 根据二叉树创建字符串

Similar Question

leading to the advanced question

Solution Tips

方案一: DFS

var tree2str = function(root) {
    // 前序遍历, 关键在于对节点的处理

    if (root === null) return '';

    const pre = `${root.val}`
    const left = root.left || root.right ? `(${tree2str(root.left)})` : '';
    const right =  root.right? `(${tree2str(root.right)})` : '';

    return pre + left + right;
};

console.log(tree2str(tree.root))

前序遍历的迭代形式, 没必要细究了, 本来遍历的迭代形式最多就是考考最常见的前中后序就已经够难了